package com.sixmac.service.impl;

import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.toolbox.CMap;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.core.toolbox.support.Convert;
import com.sixmac.model.*;
import com.sixmac.service.SimulateService;
import org.junit.Test;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;

/**
 * Created by admin on 2018/7/12.
 */
@Service
public class SimulateServiceImpl implements SimulateService {


    public AjaxResult saveResult(ClienUser user, Integer examinId, String totals) {
        AjaxResult res = new AjaxResult();
        Integer i = 0;
        Integer c = 0;
        Map<String, String> map = Db.selectOne("select count(*) as 'c' from t_examin_topic where examineId = #{examineId}", CMap.init().put("examineId", examinId));
        Integer count = Convert.toInt(map.get("c"));
        Examin examin = Blade.create(Examin.class).findById(examinId);

        ExaminRecordExtend examinRecordExtend = new ExaminRecordExtend();
        examinRecordExtend.setExaminId(examinId);
        examinRecordExtend.setContent(totals);
        examinRecordExtend.setUserId(user.getId());
        Blade.create(ExaminRecordExtend.class).save(examinRecordExtend);

        if (examin == null) {
            return res.addError("考试找不到 ");
        }
        //获取到所有题目
        List<Map> lists = JsonKit.parse(totals, List.class);
        //获取到所有正确的考试题目
        Integer success = 0;
        for (Map m : lists) {
            Integer id = Convert.toInt(m.get("id"));
            String choice = Convert.toStr(m.get("choice"));
            ExaminTopic examinTopic = Blade.create(ExaminTopic.class).findById(id);
            if (examinTopic == null) {
                continue;
            }
            //去除json中结尾的,
            if (choice.endsWith(",")) {
                choice = choice.substring(0, choice.length() - 1);
            }
            System.out.println(examinTopic.getIsTrue());
            System.out.println(choice);
            System.out.println(Convert.toStr(choice).equals(examinTopic.getIsTrue()));
            if (!Convert.toStr(examinTopic.getIsTrue()).equals(Convert.toStr(choice))) {
                //记录错题
                ExamineTopicError examineTopicError = new ExamineTopicError();
                examineTopicError.setTopicId(id);
                examineTopicError.setUserId(user.getId());
                examineTopicError.setDeleteKey(2);
                examineTopicError.setChoice((examinTopic.getIsTrue()));
                examineTopicError.setCreatetime(new Date());
                examineTopicError.setExaminId(examinId);
                Blade.create(ExamineTopicError.class).save(examineTopicError);
                ++i;
                ++c;
            } else {
                //记录正确题目数量
                ++success;

            }
        }
//        if (lists.size() < count) {
//            i += count - lists.size();
//        }
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(0);
        double t1 = (Convert.toLong(map.get("c")));//考试总题目
        double t2 = Convert.toLong(100) / t1;//每题多少分数
        double t3 = (success);//作对多少题目(总题目数量-正确数量)
        String result = numberFormat.format(t3 * t2);
        Integer p1 = Convert.toInt(examin.getPass());
        BigDecimal p2 = new BigDecimal(result);
        //生成考试记录
        ExaminRecord examinRecord = new ExaminRecord();
        examinRecord.setExaminId(examinId);
        examinRecord.setUserId(user.getId());
        examinRecord.setError(c);
        if (p2.compareTo(new BigDecimal(p1)) >= 0) {
            examinRecord.setPass(1);
        } else {
            examinRecord.setPass(2);
        }
        examinRecord.setCreatetime(new Date());
        examinRecord.setSource(result);
        examinRecord.setTotal(Convert.toStr(lists.size()));
        examinRecord.setCreatetime(new Date());
        Blade.create(ExaminRecord.class).save(examinRecord);
        res.setData(CMap.init().put("source", result).put("errorCount", Convert.toInt(t1 - t3)));

        return res;
    }

    @Test
    public void te() {
        String s = "12";
        System.out.println(s.endsWith(","));
        System.out.println(s.substring(0, s.length() - 1));
    }


    @Override
    public AjaxResult saveResult(ClienUser user, Integer examinId, Integer source, Integer total, String error) {
        AjaxResult res = new AjaxResult();
        Map<String, String> map = Db.selectOne("select count(*) as 'c' from t_examin_topic where examineId = #{examineId}", CMap.init().put("examineId", examinId));
        Examin examin = Blade.create(Examin.class).findById(examinId);
        if (examin == null) {
            return res.addError("考试找不到 ");
        }
        List<Map> lists = JsonKit.parse(error, List.class);
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(0);
        double t1 = (Convert.toLong(map.get("c")));//考试总题目
        double t2 = Convert.toLong(100) / t1;//每题多少分数
        double t3 = (Convert.toLong(map.get("c"))) - (lists.size());//作对多少题目
        String result = numberFormat.format(t3 * t2);
        Integer p1 = Convert.toInt(examin.getPass());
        BigDecimal p2 = new BigDecimal(result);
        //生成考试记录
        ExaminRecord examinRecord = new ExaminRecord();
        examinRecord.setExaminId(examinId);
        examinRecord.setUserId(user.getId());
        examinRecord.setError(lists.size());
        if (p2.compareTo(new BigDecimal(p1)) >= 0) {
            examinRecord.setPass(1);
        } else {
            examinRecord.setPass(2);
        }
        examinRecord.setCreatetime(new Date());
        examinRecord.setSource(result);
        examinRecord.setTotal(Convert.toStr(total));
        examinRecord.setCreatetime(new Date());
        Blade.create(ExaminRecord.class).save(examinRecord);
        //生成错题记录
        for (Map m : lists) {
            ExamineTopicError examineTopicError = new ExamineTopicError();
            examineTopicError.setCreatetime(new Date());
            examineTopicError.setExaminId(examinId);
            examineTopicError.setTopicId(Convert.toInt(m.get("id")));
            examineTopicError.setChoice(Convert.toStr(m.get("choice")));
            examineTopicError.setUserId(user.getId());
            examineTopicError.setDeleteKey(2);
            Blade.create(ExamineTopicError.class).save(examineTopicError);
        }
        Map m = CMap.init().put("source", result);
        return res.setData(m);
    }

    public HashSet<Map> getAllError(Integer userId, Integer examinId) {
        List<ExamineTopicError> examineTopicErrors = Blade.create(ExamineTopicError.class).findBy("userId = #{uid} and examinId = #{examinId} and deleteKey=2 group by examinId", CMap.init().put("uid", userId).put("examinId", examinId));
        HashSet<Map> set = new HashSet();
        for (ExamineTopicError examineTopicError : examineTopicErrors) {
            Map m = new HashMap();
            m.put("id", examineTopicError.getId());
            m.put("choice", examineTopicError.getChoice());
            set.add(m);
        }
        return set;
    }


//    public AjaxResult getUserExaminRecord(ClienUser user, Integer examinId) {
//        HashSet<Map> set1 = this.getAllError(user.getId(), examinId);//获取自己错误的题目
//        List<Map> list = Db.selectList(" select t.id,t.examineId,t.name,t.choice,t.image,t.reach,t.isTrue,a.content from t_examin_topic t inner join t_examin_topic_answer a on t.id=a.topicId  where 1=1 and examineId =#{examineId}", CMap.init().put("examineId", examinId));
//        return new AjaxResult().setData(CMap.init().put("error", set1).put("list", list));
//    }

    public AjaxResult getUserExaminRecord(ClienUser user, Integer examinId) {
        AjaxResult res = new AjaxResult();
        ExaminRecordExtend examinRecordExtend = Blade.create(ExaminRecordExtend.class).findFirstBy("userId =#{userId} and examinId = #{examinId}", CMap.init().put("userId", user.getId()).put("examinId", examinId));
        if (examinRecordExtend == null) {
            return res.addError("考试记录找不到");
        }
        String result = examinRecordExtend.getContent();
        Map m = Db.selectOne("select group_concat(id) as ids from t_examin_topic where examineId=#{examinId}", CMap.init().put("examinId", examinId));
        m.put("result", result);
        return res.setData(m);
    }


}
